package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端进行键盘录入登录用户名，
 * 服务器校验：
 * 如果存在，服务打印***登录，返回客户端，登录成功
 * 不存在，服务器打印***尝试登陆，返回客户端消息：用户名不存在
 * <p>
 * 客户端只能发三次
 */
class UserThread implements Runnable {
	private Socket socket;

	public UserThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		String ip = socket.getInetAddress().getHostAddress();
		System.out.println(ip + "已连接。。。。。。。。");
		try {
			boolean flag = true;

			for (int i = 0; i < 3; i++) {
				BufferedReader br = new BufferedReader(new FileReader("D:\\Study\\IDEA\\vue\\FileWriter\\src\\网络编程\\TCP连接\\客服端和服务端\\username.txt"));
				BufferedReader brr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
				String line;
				//获取客户端输入的信息
				String name = brr.readLine();
				//遍历文件中已经存在的用户信息
				while ((line = br.readLine()) != null) {
					if (line.equals(name)) {
						pw.println("欢迎：" + line + "登录");
						System.out.println(line + "已登录");
						flag = false;
						break;
					}
				}
				if (flag) {
					System.out.println(name + "尝试登录");
					pw.println("用户名：" + name + "不存在");
				}
			}
			socket.close();
		} catch (Exception e) {
			throw new RuntimeException("校验失败");
		}
	}
}

class Server7 {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(12000);
		while (true) {
			Socket accept = serverSocket.accept();
			new Thread(new UserThread(accept)).start();
		}

	}
}

class Client7 {
	public static void main(String[] args) throws IOException {
		Socket socket = new Socket("192.168.234.1", 12000);
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
		BufferedReader brr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		//因为客户端只能发三次，这里用for循环

		for (int i = 0; i < 3; i++) {
			String line = br.readLine();
			if (line == null) {
				break;
			}
			pw.println(line);
			String s = brr.readLine();
			System.out.println("info" + s);
			if (s.contains("欢迎")) {
				break;
			}
		}
		br.close();
		socket.close();
	}
}
